#! /usr/bin/python3

"""
改变对象的字符串显示
    改变对象实例的打印或者显示输出，让他们更具可读性
    要改变一个实例的字符串显示, 可重新定义它的__str__()和__repr__()方法
    repr()  : 返回__repr__()返回的字符串
    str()   : 返回__str__()返回的字符串
"""
class Pair:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return 'Pair({0.x!r}, {0.y!r})'.format(self)

    def __str__(self):
        return '({0.x!s}, {0.y!s})'.format(self)


def pair_output():
    p = Pair(3, 4)
    print(p)            # __str__
    print(str(p)) 
    print(repr(p))
    print("p is {0!r}".format(p))   #!r：格式化代码，指明使用的字符串表现形式
    print("p is {0!s}".format(p))



"""
"{0}".format(self); 变量替换时三个方法的优先级 
    __format__
    __str__
    __repr__
"""
class Date:
    _formats = {
        "ymd" :  "{d.year}--{d.month}--{d.day}",
        "mdy" :  "{d.month}/{d.day}/{d.year}",
        "dmy" :  "{d.day}/{d.month}/{d.year}"
    }

    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __format__(self, code):
        fmt = self._formats.get(code, "{d.year}--{d.month}--{d.day}")
        return fmt.format(d = self)
    
    def __str__(self):
        return '<Date __str__ representation>'


def date_output():
    date = Date(2025, 11, 22)

    # 调用__format__方法
    print(format(date))
    print(format(date, "mdy"))
    print(format(date, "dmy"))

    #调用__format__方法
    print("date is {:ymd}".format(date))
    print("date is {:mdy}".format(date))

    #优先调用__format__方法
    print("date is {0}".format(date))

    #指定格式码
    print("date is {0!s}".format(date))

date_output()

















